package com.ai.smlcore.util;

import java.util.Map;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;

import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Protocol;

public class CacheUtil {
	private static final Logger logger = LoggerFactory.getServiceLog(CacheUtil.class);
	// 调用成功标识
	private static final String IS_OK = Protocol.Keyword.OK.name();

	public static boolean put2Cache(String cacheKey, String value) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		String result = cluster.set(cacheKey, value);
		return IS_OK.equals(result);
	}

	public static boolean put2Cache(String cacheKey, String value, int seconds) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		String result = cluster.setex(cacheKey, seconds, value);
		return IS_OK.equals(result);
	}

	public static String getFromCache(String cacheKey) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		String str = cluster.get(cacheKey);
		return str;
	}

	public static long incr(String key) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		long keyLong = cluster.incr(key);
		if (keyLong == 900) {
			cluster.expire(key, 1);
		}
		return keyLong;
	}

	public static void delFromCache(String cacheKey) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		cluster.del(cacheKey);
	}

	public static boolean exists(String cacheKey) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		return cluster.exists(cacheKey);
	}

	public static boolean setnx(String cacheKey, String value) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		return cluster.setnx(cacheKey, value) == 1;
	}

	public static void hset(String cacheKey, String field, String value) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		cluster.hset(cacheKey, field, value);
	}

	public static Map<String, String> hgetAll(String cacheKey) throws BusinessException {
		JedisCluster cluster = JedisUtil.getCluster();
		return cluster.hgetAll(cacheKey);
	}
	
	public static boolean getLock(String cacheKey, int expires) throws BusinessException {
		if (setnx(cacheKey, String.valueOf(System.currentTimeMillis()))) {
			return true;
		}
		String currentValue = getFromCache(cacheKey);
		if (currentValue != null && Long.parseLong(currentValue) < System.currentTimeMillis() - expires * 1000) {
			put2Cache(cacheKey, String.valueOf(System.currentTimeMillis()), expires);
			return true;
		}
		return false;
	}

	public static boolean getLock(String cacheKey, String value) throws BusinessException {
		if (setnx(cacheKey, value)) {
			return true;
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			logger.error("", "", e);
		}
		return getLock(cacheKey, value);
	}
}
